<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-if="false" v-model="listQuery.lineNumber" :placeholder="$t('equipment.lineNumber')" class="filter-item" style="width: 200px" @change="handleFilter">
        <el-option v-for="item in lineOptions" :key="item.lineNumber" :label="item.lineName" :value="item.lineNumber" />
      </el-select>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate">
        {{ $t('common.creatNew') }}
      </el-button>
    </div>
    <!-- 主界面数据 -->
    <el-table
      ref="dragTable"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column :label="$t('produce.typeNo')" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.typeNo }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('produce.typeName')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.typeName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('produce.remark')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('produce.creatTime')" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" sortable="custom" prop="testTime" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.creatTime }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('produce.plantCode')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.plantCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('produce.lineCode')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.lineCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('produce.codeRules')" width="200px" align="center">
        <template slot-scope="{row}">
          <span v-if="row.codeRules !== null && row.codeRules !== ''" class="link-type" @click="handleUpdateRules(row)">{{ row.codeRules }}</span>
          <span v-if="row.codeRules === null || row.codeRules === ''" class="link-type" @click="handleCreatRules(row)">
            {{ $t('common.creatNew') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('processing.processingNumber')" width="150px" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleCheckProcessing(row)">{{ row.processingNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" width="200px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('common.edit') }}
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 新建和更新对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 600px; margin-left:50px;">
        <el-form-item :label="$t('produce.typeNo')" required prop="typeNo">
          <el-input v-model="temp.typeNo" :placeholder="$t('produce.typeNo')" />
        </el-form-item>
        <el-form-item :label="$t('produce.typeName')">
          <el-input v-model="temp.typeName" :placeholder="$t('produce.typeName')" />
        </el-form-item>
        <el-form-item :label="$t('produce.remark')">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
        </el-form-item>
        <el-form-item :label="$t('produce.plantCode')">
          <el-input v-model="temp.plantCode" :placeholder="$t('produce.plantCode')" />
        </el-form-item>
        <el-form-item :label="$t('produce.lineCode')">
          <el-input v-model="temp.lineCode" :placeholder="$t('produce.lineCode')" />
        </el-form-item>
        <el-form-item :label="$t('processing.processingNumber')">
          <el-select v-model="temp.processingNumber" :placeholder="$t('processing.processingNumber')" class="filter-item" style="width: 200px" @change="handleFilter">
            <el-option v-for="(item, index) in processingList" :key="index" :label="item.processingNumber" :value="item.processingNumber" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 新建和更新编码规则对话框 -->
    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="rulesDialogFormVisible">
      <div class="editor-container">
        <dnd-list :list1="codeList" :list2="optionCardList" :list1-title="$t('produce.codeRules')" :list2-title="$t('produce.optionCard')" @pushEle="rulesUpdate" />
      </div>
      <h1>
        {{ $t('produce.codeRules') +'  '+ codeTemp }}
      </h1>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rulesDialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="updateRuleData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLineList } from '@/api/equipment'
import { getTypeList, creatType, updateType, deleteType } from '@/api/produce'
import { getProcessingList } from '@/api/processing'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import i18n from '@/lang'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import DndList from '@/components/DndList2'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'TypeDef',
  components: {
    DndList,
    Pagination
  },
  directives: { waves, elDragDialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      editRight: true,
      tableKey: 0,
      list: [],
      sortable: null,
      codeTemp: '',
      codeList: [],
      lineOptions: [],
      processingList: [],
      optionCardList: [
        { id: 1, title: i18n.t('produce.typeNo'), value: '', code: '{typeNo}' },
        { id: 2, title: i18n.t('produce.plantCode'), value: '', code: '{palntCode}' },
        { id: 3, title: i18n.t('produce.lineCode'), value: '', code: '{lineCode}' },
        { id: 4, title: i18n.t('produce.timeCode'), value: '', code: '{timeCode}' },
        { id: 5, title: i18n.t('produce.sequenceCode'), value: '', code: '{sequenceCode}' },
        { id: 6, title: i18n.t('produce.monthCode'), value: '', code: '{monthCode}' },
        { id: 7, title: i18n.t('produce.dayCode'), value: '', code: '{dayCode}' },
        { id: 8, title: i18n.t('produce.sequenceCode2'), value: '', code: '{sequenceCode2}' }],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        lineId: 0,
        lineNumber: '',
        lineName: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+sequence'
      },
      showReviewer: false,
      showRemark: false,
      temp: {
        typeId: 1,
        typeNo: '',
        typeName: '',
        lineNumber: '',
        remark: '',
        plantCode: '',
        codeRules: '',
        lineCode: '',
        processingNumber: ''
      },
      dialogFormVisible: false,
      rulesDialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        typeNo: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        typeName: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        lineNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        processNumber1: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        processName1: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false,
      searchLoading: {
        director: false
      },
      searchDialogStatus: '',
      searchDialogFormVisible: {
        director: false
      }
    }
  },
  watch: {
    $route: {
      handler(val) {
        if (this.$route.query.lineNumber !== undefined) {
          this.listQuery.lineNumber = this.$route.query.lineNumber
          this.getLineList()
          this.getList()
        }
      }
    }
  },
  created() {
    document.body.ondrop = function(event) {
      event.preventDefault()
      event.stopPropagation()
    }
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
    this.listQuery.lineNumber = this.$store.getters.lineNumber
    this.getLineList()
    this.getList()
  },
  methods: {
    timestepToolTip(index) {
      return index + '%'
    },
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    isEmptyLineId: function() {
      var ret = (this.listQuery.lineNumber === undefined || this.listQuery.lineNumber === '')
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.tip'),
          message: i18n.t('msg.NO_LINE_SELECTED'),
          type: 'success',
          duration: 2000
        })
      }
      return ret
    },
    // 获取线体清单
    getLineList() {
      this.listLoading = true
      getLineList(this.listQuery).then(response => {
        this.lineOptions = response.data.lines
        this.listLoading = false
      })
    },
    // 获取工艺路径定义
    getProcessingList() {
      this.processingList = []
      if (this.isEmptyLineId() === false) {
        this.listLoading = true
        getProcessingList(this.listQuery).then(response => {
          this.processingList = response.data.processingDefs
          this.listLoading = false
        })
      }
    },
    // 获取清单
    getList() {
      this.getProcessingList()
      if (this.isEmptyLineId() === false) {
        this.listLoading = true
        getTypeList(this.listQuery).then(response => {
          this.list = response.data.types
          this.total = response.data.total
          this.listLoading = false
        })
      }
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp = {
        typeId: 1,
        typeNo: '',
        typeName: '',
        lineNumber: '',
        remark: '',
        plantCode: '',
        codeRules: '',
        lineCode: '',
        processingNumber: ''
      }
    },
    handleCheckProcessing(row) {
      const ret = Object.assign({}, row) // copy obj
      this.$router.push({ path: '/processing/processingCreate', query: { lineNumber: ret.lineNumber,
        typeNo: ret.typeNo,
        processingNumber: ret.processingNumber }})
    },
    // 更新规则
    rulesUpdate() {
      this.codeTemp = ''
      this.temp.codeRules = ''
      this.codeList.forEach(ele => {
        switch (ele.id) {
          case 1:
            ele.value = this.temp.typeNo
            break
          case 2:
            ele.value = this.temp.plantCode
            break
          case 3:
            ele.value = this.temp.lineCode
            break
          case 4:
            ele.value = '220517'
            break
          case 5:
            ele.value = '0000001'
            break
          case 6:
            ele.value = '05'
            break
          case 7:
            ele.value = '17'
            break
          case 8:
            ele.value = '000000001'
            break
        }
        this.codeTemp = this.codeTemp + ele.value
        this.temp.codeRules = this.temp.codeRules + ele.code
        console.log(this.codeTemp, this.temp.codeRules)
      })
    },
    // 创建一个规则
    handleCreatRules(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.codeList = []
      this.dialogStatus = 'create'
      this.rulesDialogFormVisible = true
      this.rulesUpdate()
    },
    // 更新一个规则
    handleUpdateRules(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.rulesDialogFormVisible = true
      this.codeList = []
      this.temp.codeRules.split('}').forEach(ele => {
        this.optionCardList.forEach(e => {
          if (e.code === ele + '}') {
            this.codeList.push(e)
            return
          }
        })
      })
      this.rulesUpdate()
    },
    // 更新数据到数据库
    updateRuleData() {
      updateType(this.temp).then(response => {
        const index = this.list.findIndex(v => v.typeId === this.temp.typeId)
        this.list.splice(index, 1, response.data)
        this.rulesDialogFormVisible = false
        this.$notify({
          itle: this.$i18n.t('common.tip'),
          message: i18n.t('msg.UPDATE_SUCCESS'),
          type: 'success',
          duration: 2000
        })
      })
    },
    // 新建一个工站
    handleCreate() {
      if (this.isEmptyLineId() === false) {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    // 创建数据
    createData() {
      this.temp.lineNumber = this.listQuery.lineNumber
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          creatType(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.CREAT_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateType(this.temp).then(response => {
            const index = this.list.findIndex(v => v.typeId === this.temp.typeId)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除数据库信息
    handleDelete(row, index) {
      this.$confirm(i18n.t('msg.DELET_INFO_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.temp = Object.assign({}, row) // copy obj
          deleteType(this.temp).then(() => {
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.DELET_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.getList()
          })
        })
        .catch(err => { console.error(err) })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
